# -*- coding: utf-8 -*-
import os
import time
import types

import jsonpath
from dateutil.parser import parse

from utils.logger import log


def search(string, start_str, end_str):
    list_1 = []
    start_str_len = len(start_str)
    start_index = string.find(start_str)
    new_str = string[start_index:]
    if start_index >= 0:
        symbol_len = start_str_len
        end_index = new_str.find(end_str)
        if end_index != -1:
            list_1 = search(new_str[symbol_len:], start_str, end_str)
            list_1.append(new_str[symbol_len:end_index])
            return list_1
    else:
        log.info("在字符串中找不到（%s）" % start_str)
        return list_1


# 更换路径分割符
def get_path(path):
    sep = '/'
    if r"/" in path:
        path = path.replace(r"/", sep)
    if "\\" in path:
        path = path.replace("\\", '/')
    return path


def get_target_value(obj, key):
    """
    获取JSON数据中对应key的值
    :param obj:dict，传入字典对象
    :param key:str，传入格式： key.match_num 键名称.第几个
    :return:
    """
    print("传入的obj:", obj)
    if not isinstance(obj, dict):
        msg = "TypeError: 类型传入错误，只支持字典类型."
        log.error(msg)
        raise TypeError(msg)
    # 当传入的key值包含多层结构时，取最后一层key的值
    if "." in str(key):
        temp_value, match_num = str(key).split(".")
        match_num = int(match_num)
    else:
        temp_value = str(key)
        match_num = 0
    expr = "$..%s" % str(temp_value)
    if jsonpath.jsonpath(obj, expr):
        data = jsonpath.jsonpath(obj, expr)
        print('提取的整体内容：', data)
        if match_num < len(data):
            value = data[match_num]
            return value
        else:
            msg = "超过列表最大索引，最大索引为: %d" % len(data)
            log.error(msg)
            raise IndexError(msg)
    else:
        msg = "字典中不存在该键, %s" % str(key)
        log.error(msg)
        return ''


def time_judgment(hour=11):
    """判断执行时间"""
    result = True
    now = time.strftime('%Y-%m-%d %H:%M:%S')
    now_hour = parse(now).hour
    log.info('当前时间为%d(小时),设置的可执行时间为: 小于%d(小时).' % (now_hour, hour))
    if now_hour < hour:
        log.info("设置时间控制的用例符合执行时间，可以执行.")
    else:
        log.info('设置时间控制的用例不符合执行时间，不执行.')
        result = False
        pass
    return result
